/*
 * =====================================================================================
 *
 *       Filename:  xmllib.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  09/20/12 14:04:38
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Andyli (gl), andy.y.li@163.com
 *        Company:  gl
 *
 * =====================================================================================
 */

#include "xmllib.h"
#include <iostream>
using namespace std;

void CreateXmlFile(const char *pSavePath)
{
	TiXmlDocument doc;

     TiXmlElement *pNode = new TiXmlElement("Node");
     doc.LinkEndChild(pNode);
 
      TiXmlElement *pChild = new TiXmlElement("Child_1");
      pChild->SetAttribute("id", "1");
      pChild->SetAttribute("info", "test");
      pNode->LinkEndChild(pChild);
  
      TiXmlText *pChildText = new TiXmlText("it's the text of Child_1");
      pChild->LinkEndChild(pChildText);

    doc.SaveFile(pSavePath);
}

void ParseXml(TiXmlElement *pNode)
{
    if (!pNode)
        return ;

    TiXmlAttribute *pAttrElement = NULL;

    while(pNode)
    {
        cout<<"<"<<pNode->Value();

        pAttrElement = pNode->FirstAttribute();
        while(pAttrElement)
        {
            cout<<" "<<pAttrElement->Name()<<"="<<pAttrElement->Value()<<" ";

            pAttrElement = pAttrElement->Next();
        }
        cout<<">"<<endl;
        
        if (pNode->GetText())
            cout<<pNode->GetText()<<endl;

        ParseXml(pNode->FirstChildElement());

        cout<<"</"<<pNode->Value()<<">"<<endl; 

        pNode = pNode->NextSiblingElement();

    }
}

int ReadXml(const char *pFilePath)
{
    TiXmlDocument doc;
    if ( !doc.LoadFile(pFilePath) )
    {
        cout<<"cannot load xml file : "<< pFilePath <<endl;
        return -1;
    }

    TiXmlElement *pNode = doc.RootElement();

    ParseXml(pNode);

	return 0;
}

